<?php
namespace app\controller;

use app\service\MqttService;
use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\ConnectionSettings;

class Mqtt
{
    protected $mqtt;

    /*public function __construct()
    {
        $this->mqtt = new phpMQTT("127.0.0.1", 1883, "api_local_core");
        if (!$this->mqtt->connect(true, NULL, "lovemf", "fantsty")) {
            die("Could not connect to MQTT server");
        }
    }*/

    // 推送消息
    public function publish($topic)
    {
        $mqttService = new MqttService();
        $msg=array(
            'client_id'=>"REGISTER_FACE",
            'cmd_id'=>1111,
            'version'=>'0.2',
            'cmd'=>'create_face',
            'per_id'=>"1111",
            'per_name'=>'1111',
            'idcardNum'=>'0',
            'idcardper'=>'0',
            'img_url'=>'http://220.166.79.246:8099/user-reg-pic/2023-07/04/142947.jpg',
            'per_type'=>1,
            'usr_type'=>0,
            's_time'=>0,
            'e_time'=>4077927429
        );
        //$data = json_encode(['topic' => 'face/'.$topic.'/request', 'message' => $msg]);
        $data=json_encode($msg);
        echo $data;
        $topic='face/'.$topic.'/request';
        //$mqttService->subscribe($topic,null);
        $mqttService->publish($topic, $data);
        //$mqttService->disconnect();
        if (true) {
            return json(['status' => 'success', 'message' => 'Message sent to MQTT server.']);
        } else {
            return json(['status' => 'error', 'message' => 'Failed to send message to MQTT server.']);
        }

    }
}